import NProgress from 'nprogress';
import usePermission from '@/store/usePermission';
import useGlobalData from '@/store/useGlobalData';

export default function handleRouterPermission(router: any) {
    router.beforeEach(async (to: any, from: any, next: any) => {
        NProgress.start();
        const permission = usePermission();
        const globalData = useGlobalData();
        // 获取菜单id权限
        globalData.setMenuId(to.meta.menuId);
        if (permission.token) {
            if (to.name === 'login') {
                next({path: '/'});
                return;
            }
            if (!globalData.routeList) {
                const res: any = await globalData.getMenuList();
                res.forEach((route: any) => {
                    router.addRoute(route);
                });
                next({...to, replace: true});
                return;
            }
            next();
        } else {
            if (to.name === 'login') {
                next();
                return;
            }
            next({name: 'login'});
        }
    });
    router.afterEach(() => {
        NProgress.done();
    });
}
